/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ebookmgr;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.tree.DefaultMutableTreeNode;

/**
 *
 * @author mazhao
 */
public class SettingDialog extends JDialog{
    
    private JTextField bookStorePath = new JTextField();
    private JPanel fileExtensionPanel = null;

    public SettingDialog(Frame owner, boolean modal) {
        super(owner, modal);

        setSize(600, 400);
        setLayout(new BorderLayout());
        this.setLocation(EBookMgrUtil.getProperPosition(owner, this));
        // ==============
        // main tab panel
        // ==============
        JTabbedPane tab = new JTabbedPane();

        // ---------------
        // book store path
        // ---------------

        // folder path tab
        JPanel bookPathPanel = new JPanel();
        bookPathPanel.setLayout(new FlowLayout());

        JLabel label = new JLabel(Configuration.getUIString("SettingDialog.LabelBookStoreFolder"));
        bookPathPanel.add(label);
        
        bookStorePath.setColumns(20);
        bookStorePath.setText(getBookFolderPath());
        bookStorePath.setEditable(false);
        bookPathPanel.add(bookStorePath);


        JButton choose = new JButton(Configuration.getUIString("SettingDialog.Choose"));
        choose.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                clickChoose();
            }

        });
        bookPathPanel.add(choose);

        tab.add(Configuration.getUIString("SettingDialog.TabLabel1"), bookPathPanel);

        // for other tab
        fileExtensionPanel =  initBookFileExtensionPanel();
        
        tab.add(Configuration.getUIString("SettingDialog.TabLabel2"), fileExtensionPanel);

        add(tab, BorderLayout.CENTER);


        // ==============
        // down panel
        // ==============
        JPanel downPanel = new JPanel();
        FlowLayout fl = new FlowLayout(FlowLayout.RIGHT);
        downPanel.setLayout(fl);

        JButton cancelBtn = new JButton(Configuration.getUIString("SettingDialog.Cancel"));
        cancelBtn.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                clickCancel();
            }
        
        });

        JButton okBtn = new JButton(Configuration.getUIString("SettingDialog.Ok"));
        okBtn.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                clickOk();
            }
        
        });

        downPanel.add(cancelBtn);
        downPanel.add(okBtn);

        add(downPanel, BorderLayout.SOUTH);

    }

    // ========================================
    // Init Panel
    // ========================================
    private JPanel initBookFileExtensionPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());
        
        List<String> allExt = Configuration.getAllFileExtension();
        List<String> selExt = Configuration.getSelectedFileExtension();

        for(String ex : allExt) {
            JCheckBox cb = null;
            if(selExt.contains(ex)) {
                cb = new JCheckBox(ex, true);
            } else {
                cb = new JCheckBox(ex, false);
            }
            panel.add(cb);
        }

        return panel;
    }


    // ========================================
    // Event Listener Method
    // ========================================
    private void clickOk() {
        clickOkChangeBookFolder();
        clickOkChangeSelectedExtension();

        this.setVisible(false);

        JOptionPane.showMessageDialog(this.getParent(), Configuration.getUIString("SettingDialog.SettingSuccessMsg"));
    }

    private void clickOkChangeBookFolder() {
        String orgPath = Configuration.getBaseFolderPath();
        String newPath = bookStorePath.getText();

        MainFrame mf = (MainFrame) this.getParent();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) mf.getCatalogTree().getModel().getRoot();
        CatalogUserObject userObj = (CatalogUserObject) root.getUserObject();
        String bookFolderName = userObj.getName();

        orgPath = orgPath  + Configuration.FILE_SEP + bookFolderName;
        newPath = newPath  + Configuration.FILE_SEP + bookFolderName;

        if (orgPath.equals(newPath)) {
            System.out.println("does not change folder path");
            return;
        } else {

            Configuration.saveBaseFolderPath((new File(newPath)).getParentFile().getAbsolutePath());
            File[] allbooks = EBookMgrUtil.listAllFiles(orgPath, true);
            for (File book : allbooks) {
                String newbookPath = book.getAbsolutePath().replace(orgPath, newPath);
                File folder = (new File(newbookPath)).getParentFile();
                if (!folder.exists()) {
                    folder.mkdirs();
                }
                boolean ret = book.renameTo(new File(newbookPath));
                System.out.println("move:" + ret);
                System.out.println("from:" + book.getAbsolutePath());
                System.out.println("to:" + newbookPath);
            }
        }
    }

    private void clickOkChangeSelectedExtension() {
        List<String> selexts = new ArrayList<String>();

        Component[] components = fileExtensionPanel.getComponents();
        for(Component c : components) {
            JCheckBox cb = (JCheckBox)c;
            if(cb.isSelected()) {
                selexts.add(cb.getText());
            }
        }

        Configuration.saveSelectedFileExtension(selexts);
    }

    private String getBookFolderPath() {
        String baseFolderPath = Configuration.getBaseFolderPath();
        return baseFolderPath;
    }

    private void clickCancel() {
        this.setVisible(false);
    }

    private void clickChoose() {
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setMultiSelectionEnabled(false);

        int ret = fc.showOpenDialog(this);

        // if choose:
        if (ret == JFileChooser.APPROVE_OPTION) {
            File chooseFile = fc.getSelectedFile();
            bookStorePath.setText(chooseFile.getAbsolutePath());

        }
    }
}
